package com.example.newsapp.model.repository;

import android.app.Application;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import androidx.lifecycle.MutableLiveData;
import com.example.newsapp.database.AppDatabase;
import com.example.newsapp.dao.UserDao;
import com.example.newsapp.model.entity.User;

public class UserRepository {
    private UserDao userDao;
    private SharedPreferences sharedPreferences;
    private MutableLiveData<User> loginResult = new MutableLiveData<>();
    private MutableLiveData<String> registerResult = new MutableLiveData<>();
    private MutableLiveData<User> currentUser = new MutableLiveData<>();
    private MutableLiveData<String> changePasswordResult = new MutableLiveData<>();
    private static final String PREF_NAME = "user_pref";
    private static final String KEY_LOGGED_IN_USER_ID = "logged_in_user_id";

    public UserRepository(Application application) {
        AppDatabase db = AppDatabase.getInstance(application);
        userDao = db.userDao();
        sharedPreferences = application.getSharedPreferences(PREF_NAME, Application.MODE_PRIVATE);
    }

    public MutableLiveData<User> getLoginResult() {
        return loginResult;
    }

    public MutableLiveData<String> getRegisterResult() {
        return registerResult;
    }

    public MutableLiveData<User> getCurrentUser() {
        return currentUser;
    }

    public MutableLiveData<String> getChangePasswordResult() {
        return changePasswordResult;
    }

    // 登录
    public void login(String username, String password) {
        new AsyncTask<Void, Void, User>() {
            @Override
            protected User doInBackground(Void... voids) {
                return userDao.getUser(username, password);
            }

            @Override
            protected void onPostExecute(User user) {
                if (user != null) {
                    // 保存登录用户ID
                    saveLoggedInUserId(user.getId());
                    currentUser.setValue(user);
                }
                loginResult.setValue(user);
            }
        }.execute();
    }

    // 注册
    public void register(String username, String password, String email) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                if (userDao.getUserByUsername(username) != null) {
                    return "用户名已存在";
                }
                User user = new User(username, password, email);
                userDao.insert(user);
                return "注册成功";
            }

            @Override
            protected void onPostExecute(String result) {
                registerResult.setValue(result);
            }
        }.execute();
    }

    // 加载当前用户信息
    public void loadCurrentUser() {
        new AsyncTask<Void, Void, User>() {
            @Override
            protected User doInBackground(Void... voids) {
                int userId = getLoggedInUserId();
                if (userId != -1) {
                    return userDao.getUserById(userId);
                }
                return null;
            }

            @Override
            protected void onPostExecute(User user) {
                currentUser.setValue(user);
            }
        }.execute();
    }

    // 修改密码
    public void changePassword(String oldPassword, String newPassword) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                int userId = getLoggedInUserId();
                if (userId != -1) {
                    User user = userDao.getUserById(userId);
                    if (user != null && user.getPassword().equals(oldPassword)) {
                        user.setPassword(newPassword);
                        userDao.update(user);
                        return "密码修改成功";
                    }
                }
                return "原密码错误";
            }

            @Override
            protected void onPostExecute(String message) {
                changePasswordResult.setValue(message);
            }
        }.execute();
    }

    // 退出登录
    public void logout() {
        clearLoggedInUserId();
        currentUser.setValue(null);
    }

    // 检查是否已登录
    public boolean isLoggedIn() {
        return getLoggedInUserId() != -1;
    }

    // 保存登录用户ID
    private void saveLoggedInUserId(int userId) {
        sharedPreferences.edit()
                .putInt(KEY_LOGGED_IN_USER_ID, userId)
                .apply();
    }

    // 获取登录用户ID
    private int getLoggedInUserId() {
        return sharedPreferences.getInt(KEY_LOGGED_IN_USER_ID, -1);
    }

    // 清除登录用户ID
    private void clearLoggedInUserId() {
        sharedPreferences.edit()
                .remove(KEY_LOGGED_IN_USER_ID)
                .apply();
    }
}